package com.example.user.aspect;

import com.example.user.annotation.CheckPoint;
import com.example.user.entity.User;
import com.example.user.enumerate.OperateTypeEnum;
import com.example.user.event.UserNotifyEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 切面处理埋点数据
 */
@Aspect
@Component
@Slf4j
public class CheckPointAspect {

    @Resource
    ApplicationEventPublisher applicationEventPublisher;

    /**
     * 以 CheckPoint 注解为切入点
     */
    @Pointcut("@annotation(com.example.user.annotation.CheckPoint)")
    public void point() {
    }

    /**
     * 环绕通知
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("point()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result =  joinPoint.proceed();
        String customerNo = null;
        OperateTypeEnum operateTypeEnum = null;
        try {
            // todo 根据结果状态发布事件
            Boolean isPublishEvent = true;
            /*if (result instanceof Map) {
                isPublishEvent = "0000".equals(((Map) result).get("status"));
            }
            else if(result instanceof BaseResult.class) {

            }*/
            if (isPublishEvent) {
                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                Method method = methodSignature.getMethod();
                CheckPoint checkPoint = method.getAnnotation(CheckPoint.class);
                customerNo = checkPoint.customerNo();
                operateTypeEnum = checkPoint.operateType();
                log.info("customerNo={},operateType={}", customerNo, operateTypeEnum);
                if (StringUtils.isNotBlank(customerNo) && operateTypeEnum != null) {
                    Object elValue = getSpelValue(joinPoint, method, customerNo);
                    if (elValue == null || operateTypeEnum == null) {
                        log.error("CustomerNo or operateType is null,can't publish event!");
                    } else {
                        User user = User.builder().code(elValue.toString()).build();
                        // 用户通知事件
                        UserNotifyEvent userNotifyEvent = new UserNotifyEvent(user, operateTypeEnum);
                        log.info("Publish event:{}", userNotifyEvent);
                        applicationEventPublisher.publishEvent(userNotifyEvent);
                    }
                } else {
                    log.warn("不能事件发布：{},{}", customerNo, operateTypeEnum);
                }
            }
        }catch (Throwable e) {
            log.error("事件发布失败：{}", customerNo, operateTypeEnum, e);
        }
        return result;
    }

    private Object getSpelValue(ProceedingJoinPoint joinPoint, Method method, String valueEl) {
        //将注解的值中的El表达式部分进行替换
        //创建解析器
        SpelExpressionParser parser = new SpelExpressionParser();
        //获取表达式
        Expression expression = parser.parseExpression(valueEl);
        //设置解析上下文(有哪些占位符，以及每种占位符的值)
        EvaluationContext context = new StandardEvaluationContext();
        //获取参数值
        Object[] args = joinPoint.getArgs();
        //获取运行时参数的名称
        DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
        String[] parameterNames = discoverer.getParameterNames(method);
        for (int i = 0; i < parameterNames.length; i++) {
            context.setVariable(parameterNames[i], args[i]);
        }
        //解析,获取替换后的结果
        return expression.getValue(context);
    }
}